import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public final class PeerConnectionAcceptor extends Thread {

	private GlobalTorrentInfo info;
	private boolean acceptConnections;
	private ServerSocket sock;

	private PeerConnectionAcceptor (GlobalTorrentInfo info) throws IOException {
		this.info = info;
		acceptConnections = true;
		sock = new ServerSocket(TrackerInterface.clientPort);
		info.acceptor = this;
	}
	
	public static PeerConnectionAcceptor beginAccepting
	(GlobalTorrentInfo info) throws IOException {
	    PeerConnectionAcceptor p = new PeerConnectionAcceptor (info);
	    p.start();
	    return p;
	}

	public void run() {
		Socket s;
		while (acceptConnections) {
			try {
				s = sock.accept();
				s.setSoTimeout(5000);
				BufferedInputStream in = new BufferedInputStream (s.getInputStream());
				String peerID = Message.readHandshake(in, info.torrentFile);
				if (peerID != null) {
				    info.peers.startIncomingPeerConnection(s, peerID);
				} else 
					s.close();
			} catch (IOException e) {}
		}
	}

	public void stopAccepting () {
		acceptConnections = false;
		try {
			sock.close();
		} catch (IOException e) {}
		info.acceptor = null;
	}

	/*Now done in BTClient
	 * 
	 * public static void main (String[] args) throws IOException {
	    String fname = "Heroes.S02E10.HDTV.XviD-LOL.[eztv].3911062.TPB.torrent";
	    GlobalTorrentInfo info = new GlobalTorrentInfo ();
	    TorrentFile tfile = (new TorrentFileHandler ()).openTorrentFile(fname);
	    info.torrentFile = tfile;
	    TrackerInterface tracker = new TrackerInterface (tfile);
	
	    info.tracker = tracker;
	    tracker.startTracker();
	    PeerConnectionAcceptor.beginAccepting(info);
	}*/
}
